<template>
	<view class="about-container">
	  <view class="header-section">
		<view class="title-box">
		  <uni-title type="h2" title="我的班后工作报告"></uni-title>
		  <view class="subtitle">查看您的班后报告记录（仅显示班后报告）</view>
		</view>
	  </view>

	  <!-- 添加/编辑表单 -->
	  <view class="form-section">
		<view class="form-item">
		  <text class="label">日期</text>
		  <picker mode="date" :value="form.aa" @change="onDateChange">
			<view class="picker-value">{{ form.aa || '请选择日期' }}</view>
		  </picker>
		</view>
		<view class="report-section">
		  <view class="section-title">班后工作报告</view>
		  <textarea 
			class="report-input" 
			v-model="form.cc" 
			placeholder="请输入班后工作报告内容"
			:maxlength="500"
			show-confirm-bar="false"
		  ></textarea>
		  <view class="word-count">{{ (form.cc || '').length }}/500</view>
		</view>

		<!-- 照片上传部分 -->
		<view class="photo-section">
			<view class="photo-preview" v-if="photoUrl || form.dd">
				<image :src="photoUrl || form.dd" mode="widthFix" @click="previewImage" class="preview-image"></image>
				<view class="photo-actions">
					<button class="delete-btn" @click="deletePhoto">X</button>
				</view>
			</view>
			<view v-else class="photo-upload">
				<button class="upload-btn" @click="takePhoto">
					<text class="upload-icon">📷</text>
					<text>拍照</text>
				</button>
			</view>
		</view>

		<view class="form-actions">
		  <button class="submit-btn" @click="handleSubmit">{{ isEdit ? '修改报告' : '提交报告' }}</button>
		</view>
	  </view>
  
	  <view class="performance-list">
		<view v-if="loading" class="loading">
		  <uni-icons type="spinner-cycle" size="24" color="#409EFF"></uni-icons>
		  <text>加载中...</text>
		</view>
		<view v-else-if="performanceList.length === 0" class="no-data">
		  <uni-icons type="info" size="24" color="#909399"></uni-icons>
		  <text>暂无班后报告数据</text>
		</view>
		<view v-else class="performance-item" v-for="(item, index) in performanceList" :key="index" :style="{ animationDelay: index * 0.1 + 's' }">
		  <view class="item-header">
			<view class="employee-info">
			  <text class="employee-id">名称：{{ item.userName }}</text>
			  <text class="date">{{ item.aa }}</text>
			</view>
			<view class="report-section">
			  <view class="report-header">
				<text class="unit">班后报告</text>
				<view class="action-buttons">
				  <button class="edit-btn" size="mini" @click="handleEdit(item)">编辑</button>
				</view>
			  </view>
			  <view class="report-content" v-if="item.cc">
				<text class="value">{{ item.cc }}</text>
			  </view>
			  <view class="report-content empty" v-else>
				<text class="value">暂无报告</text>
			  </view>
			  <view class="photo-preview report-photo" v-if="item.dd">
				<image :src="item.dd" mode="aspectFill" @click="previewRecordImage(item.dd)" class="preview-image"></image>
			  </view>
			</view>
		  </view>
		</view>
	  </view>
	</view>
  </template>
  
  <script>
  import { listYeji, addYeji, updateYeji } from '@/api/system/yeji'
  import config from '@/config'
  import { getToken } from '@/utils/auth'
  import { uploadBanhouPhoto, submitBanhouPhoto } from '@/api/system/photo'
  export default {
	data() {
	  return {
		loading: false,
		performanceList: [],
		queryParams: {
		  pageNum: 1,
		  pageSize: 10,
		  userId: null
		},
		form: {
		  aa: '',
		  cc: '',
		  dd: '',
		  userId: null
		},
		isEdit: false,
		editId: null,
		isSubmittingPhoto: false,
		photoUrl: ''
	  }
	},
	computed: {
		formattedDate() {
			return this.form.aa ? new Date(this.form.aa).toLocaleDateString() : ''
		}
	},
	onLoad() {
	  this.getUserPerformance()
	},
	methods: {
	  getUserPerformance() {
		// 从本地存储获取用户信息
		const userInfo = uni.getStorageSync('userInfo')
		if (userInfo && userInfo.user) {
		  this.queryParams.userId = userInfo.user.userId
		  this.form.userId = userInfo.user.userId
		  this.loading = true
		  
		  listYeji(this.queryParams).then(res => {
			if (res.code === 200) {
			  // 过滤出班后报告（cc字段有值的记录），并按时间倒序排列
			  const banhouReports = res.rows.filter(item => item.cc && item.cc.trim() !== '')
			  this.performanceList = banhouReports.reverse()
			} else {
			  this.$modal.msgError(res.msg || '获取数据失败')
			}
		  }).catch(err => {
			console.error('获取数据失败：', err)
			this.$modal.msgError('获取数据失败')
		  }).finally(() => {
			this.loading = false
		  })
		} else {
		  this.$modal.msgError('未获取到用户信息')
		}
	  },
	  onDateChange(e) {
		this.form.aa = e.detail.value
	  },
	  handleEdit(item) {
		this.isEdit = true
		this.editId = item.id
		this.form.aa = item.aa
		
		this.form.cc = item.cc || ''
		this.form.dd = item.dd || ''
		
		// 滚动到表单区域
		uni.pageScrollTo({
			selector: '.form-section',
			duration: 300
		})
	  },
	  resetForm() {
		this.form.aa = ''
		this.form.cc = ''
		this.form.dd = ''
		this.isEdit = false
		this.editId = null
	  },
	  async handleSubmit() {
		if (!this.form.aa) {
		  this.$modal.msgError('请选择日期')
		  return
		}
		if (!this.form.cc) {
		  this.$modal.msgError('请输入班后工作报告内容')
		  return
		}
		// 新增：如果有新照片，先上传
		if (this.photoUrl) {
		  this.isSubmittingPhoto = true
		  try {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo || !userInfo.user || !userInfo.user.userId || !userInfo.user.userName) {
			  throw new Error('未获取到用户信息，请重新登录')
			}
			const uploadRes = await new Promise((resolve, reject) => {
			  uni.uploadFile({
				url: config.baseUrl + '/system/photo/uploadBanhouPhoto',
				filePath: this.photoUrl,
				name: 'file',
				header: {
				  'Authorization': 'Bearer ' + getToken()
				},
				success: (res) => {
				  try {
					const data = JSON.parse(res.data)
					resolve(data)
				  } catch (error) {
					reject(new Error('解析响应失败'))
				  }
				},
				fail: (err) => {
				  reject(new Error(err.errMsg || '上传失败'))
				}
			  })
			})
			if (uploadRes.code !== 200 || !uploadRes.data) {
			  throw new Error(uploadRes.msg || '图片上传失败')
			}
			this.form.dd = uploadRes.data
			this.photoUrl = ''
			this.$modal.msgSuccess('照片上传成功')
		  } catch (error) {
			this.isSubmittingPhoto = false
			this.$modal.msgError(error.message || '照片上传失败')
			return
		  }
		  this.isSubmittingPhoto = false
		}
		// 继续原有提交逻辑
		const submitData = {
		  ...this.form,
		  id: this.isEdit ? this.editId : undefined
		}
		const submitMethod = this.isEdit ? updateYeji : addYeji
		try {
		  const res = await submitMethod(submitData);
		  if (res.code === 200) {
			this.$modal.msgSuccess(this.isEdit ? '修改成功' : '提交成功');
			this.resetForm();
			await this.getUserPerformance();
		  } else {
			this.$modal.msgError(res.msg || '操作失败');
		  }
		} catch (err) {
		  console.error('操作失败：', err);
		  this.$modal.msgError('操作失败');
		}
	  },
	  async takePhoto() {
		try {
			const res = await uni.chooseImage({
				count: 1,
				sourceType: ['camera'],
				sizeType: ['compressed'],
				success: (res) => {
					this.photoUrl = res.tempFilePaths[0]
				},
				fail: (err) => {
					console.error('拍照失败:', err)
					this.$modal.msgError('拍照失败')
				}
			});
		} catch (e) {
			console.error('拍照失败：', e);
			this.$modal.msgError('拍照失败');
		}
	  },
	  deletePhoto() {
		this.photoUrl = '';
		this.form.dd = '';
	  },
	  previewImage() {
		const url = this.photoUrl || this.form.dd;
		if (url) {
			uni.previewImage({
				urls: [url],
				current: url
			});
		}
	  },
	  previewRecordImage(url) {
		if (url) {
			uni.previewImage({
				urls: [url],
				current: url
			});
		}
	  }
	}
  }
  </script>
  
  <style lang="scss" scoped>
  page {
	background-color: #f5f7fa;
  }
  
  .about-container {
	padding: 30rpx;
	min-height: 100vh;
  }
  
  .header-section {
	margin-bottom: 40rpx;
	
	.title-box {
	  text-align: center;
	  padding: 20rpx 0;
	  
	  .subtitle {
		color: #909399;
		font-size: 28rpx;
		margin-top: 10rpx;
	  }
	}
  }
  
  .form-section {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);

	.form-item {
	  margin-bottom: 20rpx;

	  .label {
		display: block;
		font-size: 28rpx;
		color: #303133;
		margin-bottom: 10rpx;
	  }

	  .picker-value {
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #303133;
	  }

	  .report-input {
		width: 100%;
		height: 300rpx;
		padding: 20rpx;
		background-color: #f8f9fa;
		border: 2rpx solid #dcdfe6;
		border-radius: 8rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		margin-top: 10rpx;
	  }
	}

	.form-actions {
	  margin-top: 30rpx;

	  .submit-btn {
		width: 100%;
		background: #409EFF;
		color: #fff;
		border: none;
		border-radius: 10rpx;
		padding: 20rpx 0;
		font-size: 30rpx;

		&:active {
		  opacity: 0.8;
		}
	  }
	}

	.report-section {
		margin-bottom: 30rpx;
		padding: 20rpx;
		border: 2rpx solid #e4e7ed;
		border-radius: 12rpx;
		background-color: #fff;
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
			padding-bottom: 16rpx;
			border-bottom: 2rpx solid #e4e7ed;
		}
		
		&:first-child {
			border-color: #409eff;
			.section-title {
				color: #409eff;
				border-bottom-color: #409eff;
			}
		}
		
		/* &:nth-child(3) {
			border-color: #e6a23c;
			.section-title {
				color: #e6a23c;
				border-bottom-color: #e6a23c;
			}
		} */
	}

	.photo-section {
		margin: 20rpx 0;
		
		.photo-preview {
			position: relative;
			width: 100%;
			border-radius: 12rpx;
			overflow: hidden;
			background: #f8f9fa;
			
			.preview-image {
				width: 100%;
				display: block;
			}
			
			.photo-actions {
				position: absolute;
				top: 10rpx;
				right: 10rpx;
				
				.delete-btn {
					width: 60rpx;
					height: 60rpx;
					padding: 0;
					line-height: 60rpx;
					text-align: center;
					background: rgba(0, 0, 0, 0.5);
					color: #fff;
					border-radius: 30rpx;
					font-size: 24rpx;
					border: none;
				}
			}
		}
		
		.photo-upload {
			width: 100%;
			height: 300rpx;
			background: #f8f9fa;
			border: 2rpx dashed #dcdfe6;
			border-radius: 12rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.upload-btn {
				background: none;
				border: none;
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 10rpx;
				
				.upload-icon {
					font-size: 48rpx;
				}
				
				text {
					color: #606266;
					font-size: 28rpx;
				}
			}
		}
	}
  }
  
  .report-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;

	.action-buttons {
	  .edit-btn {
		font-size: 24rpx;
		padding: 4rpx 16rpx;
		background: #409EFF;
		color: #fff;
		border-radius: 6rpx;
		border: none;
		line-height: 1.5;
	  }
	}
  }
  
  .performance-list {
	.loading, .no-data {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  justify-content: center;
	  padding: 60rpx 0;
	  color: #909399;
	  font-size: 28rpx;
	  
	  .uni-icons {
		margin-bottom: 20rpx;
	  }
	}
	
	.performance-item {
	  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
	  border-radius: 16rpx;
	  padding: 30rpx;
	  margin-bottom: 30rpx;
	  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
	  transform: translateY(0);
	  transition: all 0.3s ease;
	  animation: slideIn 0.5s ease forwards;
	  opacity: 0;
	  
	  &:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	  }
	  
	  .item-header {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		
		.employee-info {
		  display: flex;
		  justify-content: space-between;
		  align-items: center;
		  
		  .employee-id {
			color: #303133;
			font-size: 30rpx;
			font-weight: 500;
		  }
		  
		  .date {
			color: #909399;
			font-size: 26rpx;
		  }
		}
		
		.report-section {
		  display: flex;
		  flex-direction: column;
		  gap: 10rpx;
		  
		  .report-photo {
			margin-top: 20rpx;
			border-radius: 12rpx;
			overflow: hidden;
			background: #f8f9fa;
			
			.preview-image {
				width: 100%;
				height: 300rpx;
				display: block;
				object-fit: cover;
			}
		  }
		  
		  .unit {
			font-size: 28rpx;
			color: #666;
			font-weight: bold;
		  }
		  
		  .report-content {
			background: #f8f9fa;
			border-radius: 12rpx;
			padding: 20rpx;
			max-height: 200rpx;
			overflow-y: auto;
			
			&.empty {
			  background: #f5f7fa;
			  .value {
				color: #909399;
			  }
			}
			
			.value {
			  font-size: 28rpx;
			  color: #333;
			  line-height: 1.6;
			  white-space: pre-wrap;
			  word-break: break-all;
			}
			
			&::-webkit-scrollbar {
			  width: 6rpx;
			}
			
			&::-webkit-scrollbar-thumb {
			  background-color: #dcdfe6;
			  border-radius: 3rpx;
			}
			
			&::-webkit-scrollbar-track {
			  background-color: #f5f7fa;
			}
		  }
		}
	  }
	}
  }
  
  @keyframes slideIn {
	from {
	  opacity: 0;
	  transform: translateY(20rpx);
	}
	to {
	  opacity: 1;
	  transform: translateY(0);
	}
  }

  // 添加新的样式
  .loading-spinner {
	display: inline-block;
	width: 20rpx;
	height: 20rpx;
	border: 2rpx solid #fff;
	border-radius: 50%;
	border-top-color: transparent;
	animation: spin 1s linear infinite;
	margin-right: 10rpx;
  }

  @keyframes spin {
	to {
		transform: rotate(360deg);
	}
  }

  .submit-btn-disabled {
	background: #909399 !important;
	cursor: not-allowed;
  }
  </style>
  